package com.android.sunflower.ui.plantlist

import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.lifecycle.ViewModel
import com.android.sunflower.logic.Repository
import com.android.sunflower.logic.room.entities.Flower
import com.android.sunflower.logic.room.entities.PlantedF
import com.android.sunflower.ui.flowerinfo.FlowerInfo
import com.android.sunflower.utils.ThreadPool
import java.text.FieldPosition
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlin.concurrent.thread

class PlantListViewModel:ViewModel() {
    //用来直接交给UI使用的数据
    val plantList= mutableListOf<Flower>()

    //保存搜索结果
    private val searchedPlantList= mutableListOf<Flower>()

    //保存查询出来的数据
    private val cachedAllPlants= mutableListOf<Flower>()

    //保存搜索栏的输入
    var queryText=""

    fun selectAll(){
        //使用java线程池
        val mission=object :Runnable{
            override fun run() {
                Log.d("Thread:","${Thread.currentThread().name}")
                Looper.prepare()
                plantList.addAll(Repository.selectAllFlower())
                cachedAllPlants.addAll(plantList)
                val handler=PlantListFragment.handler
                val msg=Message().apply {
                    what=PlantListFragment.querySuccess
                }
                handler?.sendMessage(msg)
                Looper.loop()
                PlantListFragment.handler?.looper?.quitSafely()
                Thread.yield()
            }
        }
        ThreadPool.exec.execute(mission)
        /*
        //使用普通Thread的方法。
        thread {
            Looper.prepare()
            plantList.addAll(Repository.selectAllFlower())
            val handler=PlantListFragment.handler
            val msg=Message()
            msg.what=888
            handler?.sendMessage(msg)
            Looper.loop()
            PlantListFragment.handler?.looper?.quitSafely()
        }*/
    }

    fun searchByName(name:String){
        searchedPlantList.clear()
        for(f in cachedAllPlants){
            if(f.name?.contains(name,false)!!){
                searchedPlantList.add(f)
            }
        }
        plantList.clear()
        plantList.addAll(searchedPlantList)
    }

    fun searchCanceled(){
        plantList.clear()
        searchedPlantList.clear()
        plantList.addAll(cachedAllPlants)
    }

    fun addToMyGarden(f:Flower){
        val pl=PlantedF(f.name,true, Date(),Date())
        val task=object :Runnable{
            override fun run() {
                Looper.prepare()
                Repository.insertPlantF(pl)
                val msg=Message().apply {
                    what=FlowerInfo.plantSuccess
                }
                FlowerInfo.handler?.sendMessage(msg)
                Looper.loop()
                FlowerInfo.handler?.looper?.quitSafely()
            }
        }
        ThreadPool.exec.execute(task)
    }
}